package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"ip_server/config"
	"ip_server/db"
	"ip_server/logger"
	"ip_server/service"
	middleware2 "ip_server/service/middleware"
	"os"

	"github.com/Unknwon/goconfig"
	"github.com/gin-gonic/gin"
	"github.com/xgdapg/daemon"
)

var _config *goconfig.ConfigFile

var isDaemon = flag.Bool("daemon", false, "running daemon mode")

func init() {
	flag.Parse()
	var err error
	_config, err = goconfig.LoadConfigFile("conf.ini")
	if err != nil {
		panic(err.Error())
	}
	//设置config对象
	config.SetConfig(_config)
	//设置日志前台可见
	db.SetConfig(db.DBConfig{
		Port:         _config.MustInt("db", "port"),
		Charset:      _config.MustValue("db", "charset"),
		Timezone:     _config.MustValue("db", "timezone"),
		DatabaseName: _config.MustValue("db", "dbname"),
		User:         _config.MustValue("db", "user"),
		Password:     _config.MustValue("db", "password"),
		Host:         _config.MustValue("db", "host"),
	})

	err = db.OpenDB()
	if err != nil {
		panic(err.Error())
	}
	logger.Init()
	logger.Info("DB init success !")
}

func main() {
	pid := 0
	ppid := 0
	if *isDaemon {
		//后台启动及看门狗进程
		daemon.Exec(daemon.Daemon | daemon.Monitor)
		pid = os.Getpid()
		ppid = os.Getppid()
		ioutil.WriteFile(_config.MustValue("server", "pidfile"), []byte(fmt.Sprintf("%d,%d", pid, ppid)), 0666)
	}

	//初始化gin服务
	svr := gin.Default()
	//加载中间件
	svr.Use(middleware2.RequestMiddleHandler)
	svr.Use(middleware2.ResponseMiddleHandler)

	//路由注册
	service.Init(svr)
	svr.Run(_config.MustValue("server", "addr"))
}
